package Internet;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
    private Socket socket = null;

    public TCPEchoClient(String serverIP,  int serverPort) throws IOException {
        this.socket = new Socket(serverIP, serverPort);
    }

    public void start() throws IOException {
        System.out.printf("[%s, %s] 客户端启动\n", socket.getInetAddress(), socket.getPort());
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while (true) {
                System.out.print("请输入请求: ");
                if (!scanner.hasNext()) {
                    System.out.printf("[%s, %s] 客户端退出\n", socket.getInetAddress(), socket.getPort());
                    break;
                }
                //获取请求
                String request = scanner.next();

                //将请求发送给服务器
                printWriter.println(request);
                //刷新缓冲区，将请求发送给服务器
                printWriter.flush();

                //获取服务器响应
                String response = scannerNet.next();

                //打印响应
                System.out.println(response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient tcpEchoClient = new TCPEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}
